import os
import sys
import time
import logging
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import threading
import uvicorn
import locale

class CloudPrintService(win32serviceutil.ServiceFramework):
    _svc_name_ = "CloudPrintService"
    _svc_display_name_ = "云打印系统服务"
    _svc_description_ = "提供云打印系统的后端服务，包括文件上传、打印队列管理和打印功能"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.is_running = False
        self.server = None
        self.server_thread = None
        
        # 设置工作目录为脚本所在目录
        self.base_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(self.base_dir)
        
        # 设置日志
        log_dir = os.path.join(self.base_dir, "logs")
        os.makedirs(log_dir, exist_ok=True)
        
        # 配置系统编码
        if sys.platform == 'win32':
            # 设置控制台编码为UTF-8
            try:
                locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
            except:
                try:
                    locale.setlocale(locale.LC_ALL, 'Chinese_China.936')
                except:
                    pass
        
        # 确保日志文件使用UTF-8编码
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(os.path.join(log_dir, "service.log"), encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger('CloudPrintService')
    
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.is_running = False
        self.logger.info('服务停止中...')
    
    def SvcDoRun(self):
        servicemanager.LogMsg(
            servicemanager.EVENTLOG_INFORMATION_TYPE,
            servicemanager.PYS_SERVICE_STARTED,
            (self._svc_name_, '')
        )
        self.is_running = True
        self.logger.info('服务启动中...')
        
        # 确保必要的目录存在
        os.makedirs(os.path.join(self.base_dir, "print_status"), exist_ok=True)
        os.makedirs(os.path.join(self.base_dir, "static"), exist_ok=True)
        os.makedirs(os.path.join(self.base_dir, "watch_folder"), exist_ok=True)
        
        # 在新线程中启动FastAPI服务
        self.server_thread = threading.Thread(target=self.run_server)
        self.server_thread.daemon = True
        self.server_thread.start()
        
        # 等待服务停止信号
        while self.is_running:
            if win32event.WaitForSingleObject(self.hWaitStop, 1000) == win32event.WAIT_OBJECT_0:
                break
            
    def run_server(self):
        try:
            # 导入应用但不直接运行它
            from app import app
            
            # 读取配置
            import configparser
            port = 8000
            host = "0.0.0.0"
            log_level = "info"
            
            try:
                config = configparser.ConfigParser()
                if os.path.exists('config.ini'):
                    config.read('config.ini', encoding='utf-8')
                    if 'Service' in config:
                        port = config.getint('Service', 'port', fallback=8000)
                        host = config.get('Service', 'host', fallback="0.0.0.0")
                        log_level = config.get('Service', 'log_level', fallback="info")
            except Exception as e:
                self.logger.error(f'读取配置文件失败: {str(e)}')
            
            self.logger.info(f'启动FastAPI服务器 {host}:{port}')
            
            # 创建配置
            config = uvicorn.Config(
                app=app, 
                host=host, 
                port=port, 
                log_level=log_level,
                log_config={
                    "version": 1,
                    "disable_existing_loggers": False,
                    "formatters": {
                        "default": {
                            "()": "uvicorn.logging.DefaultFormatter",
                            "fmt": "%(asctime)s - %(levelname)s - %(message)s",
                            "use_colors": False,
                        },
                    },
                    "handlers": {
                        "default": {
                            "formatter": "default",
                            "class": "logging.StreamHandler",
                            "stream": "ext://sys.stderr",
                        },
                        "file": {
                            "formatter": "default",
                            "class": "logging.FileHandler",
                            "filename": os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs/uvicorn.log"),
                            "encoding": "utf-8",
                        },
                    },
                    "loggers": {
                        "uvicorn": {"handlers": ["default", "file"], "level": "INFO"},
                        "uvicorn.error": {"level": "INFO"},
                        "uvicorn.access": {"handlers": ["default", "file"], "level": "INFO", "propagate": False},
                    },
                }
            )
            
            # 创建服务器
            self.server = uvicorn.Server(config)
            
            # 启动服务器
            self.server.run()
        except Exception as e:
            self.logger.error(f'启动FastAPI服务器时发生错误: {str(e)}')
            servicemanager.LogErrorMsg(f"Error: {str(e)}")

def main():
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(CloudPrintService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(CloudPrintService)

if __name__ == '__main__':
    main() 